﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using Xfm.Core.Options;

namespace Xfm.Core
{
    public class XfmService : IXfmService
    {
        public static EventId InitId = new EventId(10001);
        XfmConfig _config;
        ILogger _logger;
        public XfmService(XfmConfig xfmConfig, ILogger<XfmService> logger)
        {
            _logger = logger;
            _config = xfmConfig;
            InitOptions();
            _logger.LogDebug(InitId, "已初始化了{0}个IXfOption", _config.XfmOptions.Count);
        }
        public IXfmOption GetOption(string key)
        {
            if (_config.XfmOptions.TryGetValue(key, out IXfmOption xfOption))
            {
                return xfOption;
            }
            _logger.LogError(InitId, $"找不到配置文件 key:{key}");
            throw new NullReferenceException($"找不到配置文件key:{key}");
        }
        public T GetOptionValue<T>(string key) where T:class
        {
            var option= GetOption(key);
            return option.GetValue<T>();
        }
        public ICollection<IXfmOption> GetOptions()
        {
            return _config.XfmOptions.Values;
        }
        public void AddOption(IXfmOption option)
        {
            _config.XfmOptions.Add(option.Key, option);
        }
        public void AddOptions(IEnumerable<IXfmOption> options)
        {
            foreach (var item in options)
            {
                AddOption(item);
            }
        }
        /// <summary>
        /// options初始化
        /// </summary>
        private void InitOptions()
        {
            if (_config == null)
                throw new ArgumentNullException(nameof(XfmConfig));
            foreach (var item in _config.XfmOptions)
            {
                if (string.IsNullOrEmpty(item.Key))
                    throw new KeyNotFoundException("xfOption key不能为空");
                item.Value.Init();
                _logger.LogDebug(InitId, $"初始化XfOption key:{item.Key},type:{item.Value.ValueType}");
            }
        }
    }
}
